﻿// ******************************************************************
// * Copyright(c)  Steven Lu
// * Description   : Entity_SALES_RETURN_ORDER
// * CreateDate    : 2013/1/14 15:36:09
// * Creater       : SalesReturnOrderBs
// * LastChangeDate: 2013/1/14 15:36:09
// * LastChanger   : 2013/1/14 15:36:09
// * Version Info  : 1.0 For ESOL
// ******************************************************************

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Suzsoft.Smart.Data;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Common;


namespace ESOL.Business.Sales

{
    /// <summary>
    /// SalesReturnOrder
    /// </summary>
    public partial class SalesReturnOrderBs
    {
        #region GetByID
        /// <summary>
        /// Get Entity
        /// </summary>
        /// <param name="objSalesReturnOrderEntity">Entity</param>
        /// <returns>Entity</returns>
        public static SalesReturnOrderEntity GetSalesReturnOrder(SalesReturnOrderEntity objSalesReturnOrderEntity)
        {
            return DataAccess.SelectSingle<SalesReturnOrderEntity>(objSalesReturnOrderEntity);
        }
        public static SalesReturnOrderEntity GetSalesReturnOrderById(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return null;
            }
            SalesReturnOrderEntity entity = new SalesReturnOrderEntity();
            entity.Id = id;
            return DataAccess.SelectSingle<SalesReturnOrderEntity>(entity);
            
        }
        #endregion


        #region Insert
        /// <summary>
        /// Insert Data
        /// </summary>
        /// <param name="objSalesReturnOrderEntity">Entity</param>
        /// <returns>true Insert Succeed; false Insert Fail</returns>
        public static bool InsertSalesReturnOrder(SalesReturnOrderEntity objSalesReturnOrderEntity)
        {
            return DataAccess.Insert(objSalesReturnOrderEntity);
        }

        public static bool InsertSalesReturnOrder(List<SalesReturnOrderEntity> objSalesReturnOrderEntityList)
        {
            return DataAccess.Insert(objSalesReturnOrderEntityList);
        }
        #endregion


        #region Update
        /// <summary>
        /// Update Data
        /// </summary>
        /// <param name="objSalesReturnOrderEntity">Entity</param>
        /// <returns>true Update Succeed; false Update Fail</returns>
        public static bool UpdateSalesReturnOrder(SalesReturnOrderEntity objSalesReturnOrderEntity)
        {
            return DataAccess.Update(objSalesReturnOrderEntity);
        }

        public static bool UpdateSalesReturnOrder(List<SalesReturnOrderEntity> objSalesReturnOrderEntityList)
        {
            return DataAccess.Update<SalesReturnOrderEntity>(objSalesReturnOrderEntityList);
        }
        #endregion


        #region Delete
        /// <summary>
        /// Delete Data
        /// </summary>
        /// <param name="objSalesReturnOrderEntity">Entity</param>
        /// <returns>true Delete Succeed; false Delete Fail</returns>
        public static bool DeleteSalesReturnOrder(SalesReturnOrderEntity objSalesReturnOrderEntity)
        {
            return DataAccess.Delete(objSalesReturnOrderEntity);
        }

        public static bool DeleteSalesReturnOrder(List<SalesReturnOrderEntity> objSalesReturnOrderEntityList)
        {
            return DataAccess.Delete<SalesReturnOrderEntity>(objSalesReturnOrderEntityList);
        }
        #endregion


        #region GetAll
        /// <summary>
        /// Get All Data
        /// </summary>
        /// <returns>Back All Data<returns>
        public static DataSet GetSalesReturnOrderAll()
        {
            return DataAccess.SelectAllDataSet<SalesReturnOrderEntity>();
        }
        /// <summary>
        /// Get All Data List
        /// </summary>
        /// <returns>Back All Data List<returns>
        public static List<SalesReturnOrderEntity> GetSalesReturnOrderAllList()
        {
            return DataAccess.SelectAll<SalesReturnOrderEntity>();
        }
        #endregion

        public static bool UpdateReturn(SalesReturnOrderEntity entity, DataTable salesReturnItems, bool isNew, List<SalesReturnItemEntity> deleteSalesReturnItems, string msg)
        {
            using (DataAccessBroker broker = DataAccessFactory.Instance())
            {
                try
                {
                    broker.BeginTransaction();
                    if (isNew)
                    {
                        string code = "";
                        if (MstCodeRuleBs.GetCurrentOrderCode("SalesReturnOrder", out code, broker) == false)
                        {
                            broker.RollBack();
                            throw new Exception("自动生成发货申请单号失败！");
                        }
                        entity.OrderCode = code;
                        DataAccess.Insert(entity, broker);
                    }
                    else
                    {
                        DataAccess.Update(entity, broker);
                    }

                    //Save items

                    List<SalesReturnItemEntity> insertList = new List<SalesReturnItemEntity>();
                    List<SalesReturnItemEntity> modifyList = new List<SalesReturnItemEntity>();
                    foreach (DataRow dr in salesReturnItems.Rows)
                    {
                        SalesReturnItemEntity Item = null;
                        switch (dr.RowState)
                        {
                            case DataRowState.Added:
                                Item = new SalesReturnItemEntity(dr);
                                if (string.IsNullOrEmpty(Item.ProductId))
                                {
                                    Item.ProductId = null;
                                }
                                Item.SalesReturnOrderId = entity.Id;
                                insertList.Add(Item);
                                break;
                            case DataRowState.Modified:
                                Item = new SalesReturnItemEntity(dr);
                                if (string.IsNullOrEmpty(Item.ProductId))
                                {
                                    Item.ProductId = null;
                                }
                                Item.SalesReturnOrderId = entity.Id;
                                modifyList.Add(Item);
                                break;
                            default:
                                continue;
                        }
                    }
                    DataAccess.Delete<SalesReturnItemEntity>(deleteSalesReturnItems, broker);
                    DataAccess.Update<SalesReturnItemEntity>(modifyList, broker);
                    DataAccess.Insert<SalesReturnItemEntity>(insertList, broker);

                    //Send message
                    MstMessageEntity message = new MstMessageEntity();
                    message.MessageId = Guid.NewGuid().ToString();
                    message.MessateTitle = "审核销售退货单";
                    message.MessageBody = @"请审核一下销售退货单
申请单号：" + entity.OrderCode + @"；
申请日期：" + entity.Created.ToString("yyyy-MM-dd");
                    message.MessageDate = DateTime.Now;
                    message.MessageSender = entity.CreatedBy;
                    message.MessageLevel = "ML03";
                    message.FormName = "ESOL.WinUI.Sales.frmManageReturnOrder";
                    MstMessageBs.SendApproveMessage(message, "ESOL.WinUI.Sales.frmManageReturnOrder", "brnApprove", broker);

                    broker.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    broker.RollBack();
                    throw ex;
                }
            }
            //return false;
        }

        public static DataTable GetByCondition(string condition, string orderBy, string RowCount)
        {
            string sql = CommonFunctions.GetSelect(RowCount) + @" A.*,B.APPLICATION_CODE,C.CUSTOMER_NAME FROM dbo.SALES_RETURN_ORDER A
                           inner JOIN dbo.SALES_PROD_PLAN_APPLICATION B ON A.APPLICATION_ID=B.APPLICATION_ID
                           inner JOIN dbo.MST_CUSTOMER C ON A.CUSTOMER_ID=C.CUSTOMER_ID
                           WHERE 1=1 ";
            if (string.IsNullOrEmpty(condition) == false)
            {
                sql += condition;
            }
            if (string.IsNullOrEmpty(orderBy) == false)
            {
                sql += " ORDER BY " + orderBy;
            }
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null && ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return null;

        }

        public static DataTable GetReturnToInvItemsForCondition(string condition, string orderBy, string RowCount)
        {
            string sql = CommonFunctions.GetSelect(RowCount) + @" A.*,B.ORDER_CODE,B.ORDER_DATE,D.NAME_CN,B.APPLICATION_CODE,C.PRODUCT_CODE,C.PRODUCT_NAME,C.PRODUCT_SPEC_OUT,F.PRICE,CONVERT(DECIMAL(18,2),(F.PRICE*CONVERT(DECIMAL(18,2),A.RETURN_QTY))) AS TOTAL_AMOUNT,isnull(E.IMPORTS_QTY,0) as TOTAL_QTY,((CONVERT(DECIMAL(18,2),A.RETURN_QTY))-(CONVERT(DECIMAL(18,2),isnull(E.IMPORTS_QTY,0)))) AS REMIND_QTY,G.ORDER_CODE AS ACCOUNT_CODE
                           FROM dbo.SALES_RETURN_ITEM A
                           LEFT JOIN dbo.SALES_RETURN_ORDER B ON A.SALES_RETURN_ORDER_ID=B.ID
                           LEFT JOIN dbo.MST_PRODUCT C ON A.PRODUCT_ID=C.PRODUCT_ID
                           LEFT JOIN dbo.MST_PERSON D ON B.CREATED_BY=D.PERSON_ID
                           LEFT JOIN (SELECT SALES_RETURN_ITEM_ID,SUM(CONVERT(DECIMAL(18,2),IMPORT_QTY)) AS IMPORTS_QTY FROM dbo.INV_RETURN_IMPORT_ITEM GROUP BY SALES_RETURN_ITEM_ID) E ON A.ID=E.SALES_RETURN_ITEM_ID
                           LEFT JOIN dbo.SALES_PROD_PLAN_APPLICATION_ITEM F ON A.SALES_PROD_PLAN_APPLICATION_ITEM_ID=F.APPLICATION_ITEM_ID 
                           LEFT JOIN FIN_RETURN_ACCOUNT_ORDER G ON B.ID=G.SALES_RETURN_ORDER_ID
                           WHERE 1=1 AND B.STATUS='SRO03' ";
            if (string.IsNullOrEmpty(condition) == false)
            {
                sql += condition;
            }
            if (string.IsNullOrEmpty(orderBy) == false)
            {
                sql += " ORDER BY " + orderBy;
            }
            DataSet ds = DataAccess.SelectDataSet(sql);
            if (ds != null && ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            return null;
        }

        //public static bool ReturnAccount(List<SalesReturnItemEntity> mItems, string msg)
        //{
        //     using (DataAccessBroker broker = DataAccessFactory.Instance())
        //    {
        //        try
        //        {
        //            broker.BeginTransaction();

        //            List<SalesProdPlanApplicationEntity> mSalesProdApps = new List<SalesProdPlanApplicationEntity>();
        //            List<FinCustomerAccountItemEntity> mFinCusAcc = new List<FinCustomerAccountItemEntity>();
        //            foreach (SalesReturnItemEntity entity in mItems)
        //            {
        //                SalesReturnOrderEntity returnOrder = SalesReturnOrderBs.GetSalesReturnOrderById(entity.SalesReturnOrderId);
        //                SalesProdPlanApplicationItemEntity applicationItem = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByID(entity.SalesProdPlanApplicationItemId);
        //                SalesProdPlanApplicationEntity application = SalesProdPlanApplicationBs.GetSalesProdPlanApplicationByID(returnOrder.ApplicationId);
        //                if (application == null||applicationItem==null)
        //                {
        //                    broker.RollBack();
        //                    throw new Exception("自动生成发货申请单号失败！");
        //                }
                        
        //                application.TotalAmount = application.TotalAmount-(Convert.ToDecimal(entity.ReturnQty) * applicationItem.Price);
        //                mSalesProdApps.Add(application);


        //                string sql=@"SELECT * FROM dbo.FIN_CUSTOMER_ACCOUNT_ITEM WHERE APPLICATION_ID='"+application.ApplicationId+"'";
        //                DataSet dsFin = DataAccess.SelectDataSet(sql);
        //                FinCustomerAccountItemEntity accountItem = new FinCustomerAccountItemEntity(dsFin.Tables[0].Rows[0]);
        //                accountItem.ReceivableAmount = accountItem.ReceivableAmount - (Convert.ToDecimal(entity.ReturnQty) * applicationItem.Price);
        //                mFinCusAcc.Add(accountItem);
        //            }
        //            DataAccess.Update<SalesProdPlanApplicationEntity>(mSalesProdApps,broker);
        //            DataAccess.Update<FinCustomerAccountItemEntity>(mFinCusAcc, broker);



        //            broker.Commit();
        //            return true;
        //        }
        //        catch (Exception ex)
        //        {
        //            broker.RollBack();
        //            throw ex;
        //        }
        //    }
        //}
    }


}

